package com.GlobalPaint.app.ui.location;


import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.GlobalPaint.app.R;
import com.GlobalPaint.app.bean.MarBen;
import com.GlobalPaint.app.bean.MyFriendBean;
import com.GlobalPaint.app.bean.ReturnStatusResultEntity;
import com.GlobalPaint.app.ui.Mine.MsrActivity;
import com.GlobalPaint.app.utils.Constants;
import com.GlobalPaint.app.utils.DataManager;
import com.GlobalPaint.app.utils.UiUtil;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapViewLayoutParams;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;

import static com.GlobalPaint.app.R.drawable.qqq;


public class MyLocationFragment extends Fragment {
    private TextureMapView map_view = null;
    private BaiduMap mBaiduMap2;
    private LocationClient mLocationClient2;
    private BDLocationListener mBDLocationListener2;
    private View popView2;
    LocationClientOption option2;
    private LatLng dxu;
    private MarBen ben;
    private Button bt_fuwei;
    String userName;
    private BitmapDescriptor bitmap2;//当前点
    private MyFriendBean bean;
    int userId;
    private static final String TAG = "MyLocationFragment";
    private static final int GET_GIS = 0x0004;
    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
                case GET_GIS:
                    String url = Constants.JASON_SERVICE_URL + "/Gis/queryNewest?userName="+userName+"&userId=" + userId;
                    DataManager.getInst().getHttpRequestJsonClass(url, DataManager.userEntity.getCookie(), MarBen.class, new DataManager.Callback() {
                        @Override
                        public void onSuccess(Object o) {
                            ben = (MarBen) o;
                            if (ben.getStatus() == 1) {
                                if(ben.getData()!=null){
                                    initMarket();    //标志
                                    initPopView();
                                }
                            }
                        }

                        @Override
                        public void onFailure(ReturnStatusResultEntity error) {

                            //Toast.makeText(FriendsLocationActivity.this,gisBean.getMsg(),Toast.LENGTH_LONG).show();
                        }
                    });
                    break;
            }
        }
    };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_location, container, false);
        initView(view);
        return view;
    }

    private void initView(View view){
        popView2 = View.inflate(getContext(), R.layout.pop_view1, null);
        bt_fuwei = (Button)view. findViewById(R.id.bt_fuwei);
        userName = DataManager.userEntity.getUserName();
        userId = DataManager.userEntity.getUserId();

        bt_fuwei.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 启动定位
                mLocationClient2.start();
                mLocationClient2.restart();
                // 注册监听
                mLocationClient2.registerLocationListener(mBDLocationListener2);
            }
        });
        map_view = (TextureMapView) view.findViewById(R.id.map_view);
        //获取baidumap对象
        mBaiduMap2 = map_view.getMap();
        // 设置可改变地图位置
        mBaiduMap2.setMyLocationEnabled(true);
        //回调 获取坐标
        // 声明LocationClient类
        mLocationClient2 = new LocationClient(getContext());
        mBDLocationListener2 = new MyBDLocationListener2();
        // 声明定位参数
        option2 = new LocationClientOption();
        option2.setCoorType("bd09ll");// 设置返回定位结果是百度经纬度 默认gcj02
        //option.setScanSpan(60000);// 设置发起定位请求的时间间隔 单位ms
        option2.setIsNeedAddress(true);// 设置定位结果包含地址信息
        option2.setNeedDeviceDirect(true);// 设置定位结果包含手机机头 的方向
        // 设置定位参数
        mLocationClient2.setLocOption(option2);
        // 启动定位
        mLocationClient2.start();
        // 注册监听
        mLocationClient2.registerLocationListener(mBDLocationListener2);
        mhandler.sendEmptyMessage(GET_GIS);
    }
    private void getZB(double latitude, double longitude) {
        MapStatusUpdate loc = MapStatusUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 13);
        mBaiduMap2.setMapStatus(loc);
        LatLng point2 = new LatLng(latitude, longitude);
        //构建Marker图标
        bitmap2 = BitmapDescriptorFactory
                .fromResource(qqq);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option2 = new MarkerOptions()
                .position(point2)
                .icon(bitmap2);
        mBaiduMap2.addOverlay(option2);
    }

    private void initPopView() {
        popView2.setVisibility(View.GONE);
        if (map_view.getParent() == null) {
            map_view.addView(map_view, createLayoutParams(dxu));
        }
        mBaiduMap2.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                updatePopView(marker);
                return true;
            }
        });
    }
    private void updatePopView(final Marker marker) {
        if(marker==null){
            return;
        }
        if(marker.getTitle() == null){
            return;
        }
        final int id = Integer.parseInt(marker.getTitle());
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setMessage("是否添加"+ben.getData().get(id).getRealName()+"为好友");
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                String jid = ben.getData().get(id).getUserName();
                String nick = ben.getData().get(id).getRealName();
                String userName = DataManager.userEntity.getUserName();
                getAdd(userName,jid,nick );
            }
        });
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });
        //不关闭写法
        builder.setCancelable(false);
        builder.create();
        if (!getActivity().isFinishing()) {
            builder.show();
        }
    }


    private MapViewLayoutParams createLayoutParams(LatLng xzPos) {
        MapViewLayoutParams params = new MapViewLayoutParams.Builder()
                .layoutMode(MapViewLayoutParams.ELayoutMode.mapMode)    // 坐标类型为经纬度的类型
                .position(xzPos)    // 指定View的位置
                .yOffset(UiUtil.dp2px(-28))       // 指定View在y方向的偏移量
                .build();
        return params;
    }
    private void getAdd(String userName, String jid, String name){
        String url= Constants.JASON_SERVICE_URL+"appFriends/addAttention?userName="
                + userName +"&jid="+jid+"&nick="+name;
        DataManager.getInst().getHttpRequestJsonClass(url, DataManager.userEntity.getCookie(), MyFriendBean.class, new DataManager.Callback() {
            @Override
            public void onSuccess(Object o) {

                bean=(MyFriendBean)o;
                if (bean.getStatus() == 1){
                    Toast.makeText(getContext(),"添加成功",Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(ReturnStatusResultEntity error) {
                Toast.makeText(getContext(),"添加失败",Toast.LENGTH_LONG).show();
            }
        });
    }
    private void initMarket() {
        //创建覆盖物
        for (int i = 0; i < ben.getData().size(); i++) {
            View inflate = View.inflate(getContext(), R.layout.point, null);
            TextView dtTv = (TextView) inflate.findViewById(R.id.ditu_text);
            dtTv.setText(ben.getData().get(i).getRealName());
            Bitmap viewBitmap = getViewBitmap(inflate);
            BitmapDescriptor descriptor = BitmapDescriptorFactory.fromBitmap(viewBitmap);
            MarkerOptions options = new MarkerOptions();
            MarBen.DataBean dataListBean = ben.getData().get(i);
            options.position(new LatLng(dataListBean.getLat(), dataListBean.getLng()))
                    .icon(descriptor)
                    .draggable(true)
                    .title(String.valueOf(i));
//            optionses.add(options);
            mBaiduMap2.addOverlay(options);
        }
//        map.addOverlays(optionses);
    }
    private Bitmap getViewBitmap(View addViewContent) {

        addViewContent.setDrawingCacheEnabled(true);

        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());

        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        return bitmap;
    }
    private class MyBDLocationListener2 implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            // 非空判断
            if (location != null) {
                // 根据BDLocation 对象获得经纬度以及详细地址信息
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                String address = location.getAddrStr();
                Log.i("12345678不同页面", "address:" + address + " latitude:" + latitude
                        + " longitude:" + longitude + "---");
                dxu = new LatLng(latitude, longitude);
                getZB(latitude,longitude);

            }
        }
    }
    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        super.onResume();
        map_view.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        map_view.onPause();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocationClient2.stop();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        map_view.onDestroy();
    }
}
